'use strict';

var config = require('../config/environment');
var jwt = require('jsonwebtoken');
var expressJwt = require('express-jwt');
var compose = require('composable-middleware');
var User = require('../sqldb').User;
var _ = require('lodash');

var redis = require("redis");
var commonRedisClient = redis.createClient(config.commonRedis);

var util = require('../api/global/util');

var validateJwt = expressJwt({
    secret: config.secrets.session
});

/**
 * [formatData 替换所有用户权限标识]
 * @param  {[type]} jsonParmas [description]
 * @param  {[type]} names      [description]
 * @param  {[type]} username   [description]
 * @return {[type]}            [description]
 */
var formatData = function(jsonParmas, names, username) {
    jsonParmas = JSON.stringify(jsonParmas);
    _.map(names, function(name, index) {
        var reg = new RegExp('"' + name + '":\s*"[^\"]*"', "g");
        jsonParmas = jsonParmas.replace(reg, function(item) {
            var newItem = JSON.parse("{" + item + "}");
            var value = _.values(newItem)[0];
            value = username;
            return '"' + name + '":"' + value + '"';
        });
    });
    return JSON.parse(jsonParmas);
};

/**
 * Attaches the user object to the request if authenticated
 * Otherwise returns 403
 */
function isAuthenticated() {
    return compose()
        // Validate jwt
        .use(function(req, res, next) {
            // allow access_token to be passed through query parameter as well
            if (req.query && req.query.hasOwnProperty('access_token')) {
                req.headers.authorization = 'Bearer ' + req.query.access_token;
            }
            validateJwt(req, res, function(err) {
                // 如果有错误
                if (err) {
                    return util.formatResult({
                        message: '登录过期，请重新登录',
                        status: 401
                    }, null, res);
                } else {
                    // 无误
                    return User.findOne({
                            where: {
                                id: req.user.id
                            }
                        }).then(function(user) {
                            if (!user) {
                                return util.formatResult({
                                    message: '用户不存在',
                                    status: 401
                                }, null, res);
                            }
                            if (user.active == false) {
                                return util.formatResult({
                                    message: '账号存在异常，请联系管理员',
                                    status: 401
                                }, null, res);
                            }
                            req.user = user;
                            next();
                            return user;
                        })
                        .catch(function(err) {
                            console.log('--------------查询用户信息失败 auth.service.js User.findOne----------------');
                            console.log(err);
                            return util.formatResult({
                                message: '查询用户信息失败，请稍候重试',
                                status: 401
                            }, null, res);
                        });
                }
            });
        });
}

/**
 * Checks if the user role meets the minimum requirements of the route
 */
function hasRole(roleRequired) {
    if (!roleRequired) {
        throw new Error('Required role needs to be set');
    }
    return compose()
        .use(isAuthenticated())
        .use(function meetsRequirements(req, res, next) {
            if (_.isArray(roleRequired)) {
                if (_.indexOf(roleRequired, req.user.role) > -1) {
                    next();
                } else {
                    return util.formatResult({
                        message: '没有权限访问',
                        status: 403
                    }, null, res);
                }
            } else {
                if (req.user.role === roleRequired) {
                    next();
                } else {
                    return util.formatResult({
                        message: '没有权限访问',
                        status: 403
                    }, null, res);
                }
            }
        });
}

/**
 * Returns a jwt token signed by the app secret
 */
function signToken(user, type) {
    return jwt.sign(user, config.secrets.session, {
        expiresIn: type == 'admin' ? config.secrets.adminExpiresIn : config.secrets.expiresIn
    });
}


exports.hasRole = hasRole;
exports.signToken = signToken;
exports.isAuthenticated = isAuthenticated;
